<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="学生" prop="userId" label-width="50px">
            <el-select
              v-model="form.userId"
              placeholder="请选择学生"
              clearable
              :disabled="isDetail || isApprove"
              @change="handleUserChange"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="formUserInfo">
          <el-col :span="12">
            <el-form-item label="学校" label-width="50px">
              <el-input :value="getUniversityText(formUserInfo.trainUniversity)" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" label-width="50px">
              <el-input v-model="formUserInfo.trainMajor" disabled></el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12">
          <el-form-item label="完成入企手续办理" prop="completeJoinProcedure">
            <el-radio-group v-model="form.completeJoinProcedure" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成三方协议签订" prop="completeSignAgreement">
            <el-radio-group v-model="form.completeSignAgreement" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.completeSignAgreement === 'Y'">
          <el-form-item label="上传三方协议附件" prop="fileObjects">
            <file-upload
              v-model="form.fileObjects"
              ref="fileUploadRef"
              :limit="10"
              :fileSize="100"
              :disabled="isDetail || isApprove"
              :fileType="[
                'pdf',
                'doc',
                'docx',
                'xls',
                'xlsx',
                'ppt',
                'pptx',
                'zip',
                '7z',
                'rar',
                'jpg',
                'jpeg',
                'png',
              ]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成入企培训导入" prop="completeInductionTrain">
            <el-radio-group v-model="form.completeInductionTrain" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成办公资源配备" prop="completeAllocationResources">
            <el-radio-group v-model="form.completeAllocationResources" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成党员档案转档" prop="completeTransferParty">
            <el-radio-group v-model="form.completeTransferParty" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否入住公寓" prop="stayApartment">
            <el-radio-group v-model="form.stayApartment" :disabled="isDetail || isApprove">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 审批进度组件 -->
    <div v-if="form.approvalInfoId" style="margin-bottom: 20px">
      <approval-progress :approval-info-id="form.approvalInfoId" />
    </div>

    <!-- 审批模式下的审核意见字段 -->
    <div v-if="isApprove" style="margin-bottom: 20px">
      <el-form-item label="审核意见" prop="approvalRemark">
        <el-input
          v-model="form.approvalRemark"
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
    </div>

    <!-- 显示被驳回的审核意见 -->
    <div v-if="form.approvalStatus === 'rejected'">
      <el-form-item label="审核意见" style="margin-bottom: 0">
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
    </div>

    <!-- 页面底部按钮 -->
    <div class="dialog-footer" style="margin-top: 20px">
      <!-- 普通编辑模式按钮 -->
      <template v-if="!isApprove">
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="submitLoading"
          :disabled="submitLoading"
        >确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </template>

      <!-- 审批模式按钮 -->
      <template v-else>
        <el-button 
          type="success" 
          @click="handleApprovePass"
          :loading="approvePassLoading"
          :disabled="approvePassLoading"
        >通 过</el-button>
        <el-button 
          type="danger" 
          @click="handleApproveReject"
          :loading="approveRejectLoading"
          :disabled="approveRejectLoading"
        >驳 回</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </template>
    </div>
  </div>
</template>

<script setup name="EnterprisePracticeManageEdit">
import {
  getDetail,
  addItem,
  editItem,
} from "@/api/enterprise-practice-manage";
import { handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import FileUpload from "@/components/FileUpload";
import ApprovalProgress from "@/components/ApprovalProgress";
import { v4 as uuidv4 } from "uuid";
import { isPhone } from "@/utils/index";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_yes_no, university } = proxy.useDict("sys_yes_no", "university");

const id = route.params.id;
const mode = route.params.mode || 'edit';
const isApprove = mode === 'approve';
const isDetail = false;

const form = reactive({
  userId: undefined,
  completeJoinProcedure: "N",
  completeSignAgreement: "N",
  completeInductionTrain: "N",
  completeAllocationResources: "N",
  completeTransferParty: "N",
  stayApartment: "N",
  fileObjects: [],
  approvalRemark: "",
});

const rules = {
  userId: [{ required: true, message: "请选择学生", trigger: "change" }],
  completeJoinProcedure: [
    { required: true, message: "请选择完成入企手续办理", trigger: "change" },
  ],
  completeSignAgreement: [
    { required: true, message: "请选择完成三方协议签订", trigger: "change" },
  ],
  fileObjects: [
    { required: true, message: "请上传三方协议附件", trigger: "change" },
  ],
  completeInductionTrain: [
    { required: true, message: "请选择完成入企培训导入", trigger: "change" },
  ],
  completeAllocationResources: [
    { required: true, message: "请选择完成办公资源配备", trigger: "change" },
  ],
  completeTransferParty: [
    { required: true, message: "请选择完成党员档案转档", trigger: "change" },
  ],
  stayApartment: [
    { required: true, message: "请选择是否入住公寓", trigger: "change" },
  ],
};

const formRef = ref(null);
const fileUploadRef = ref(null);
const userList = ref([]);
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.userId)
);

/** 高校名称文本显示函数 */
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

/** 用户选择变化 */
function handleUserChange() {
  // 用户选择后会自动通过 computed 获取用户信息
}

/** 提交表单 */
function submitForm() {
  if (submitLoading.value) return;

  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;

      // 整理文件数据
      const fileObjects = fileUploadRef.value && fileUploadRef.value.fileList
        ? fileUploadRef.value.fileList.map((t) => ({
            fileName: t.name.split("/").pop(),
            filePath: t.url,
          }))
        : [];

      const submitData = {
        ...form,
        fileObjects,
      };

      if (form.id != undefined) {
        editItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          router.back();
        }).catch((error) => {
          console.error("修改失败:", error);
          submitLoading.value = false;
        });
      } else {
        addItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          router.back();
        }).catch((error) => {
          console.error("新增失败:", error);
          submitLoading.value = false;
        });
      }
    }
  });
}

/** 通过审批 */
function handleApprovePass() {
  if (approvePassLoading.value) return;

  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "approved",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    router.back();
  }).catch((error) => {
    console.error("审批通过失败:", error);
    approvePassLoading.value = false;
  });
}

/** 驳回审批 */
function handleApproveReject() {
  if (!form.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    router.back();
  }).catch((error) => {
    console.error("审批驳回失败:", error);
    approveRejectLoading.value = false;
  });
}

/** 取消操作 */
function handleCancel() {
  router.back();
}

// 初始化加载
onMounted(() => {
  // 加载学生列表
  getStudentList({ roleKey: "student" }).then((res) => {
    userList.value = res.data;
  });

  // 如果不是新增，则加载详情
  if (id !== 'add') {
    getDetail(id).then((response) => {
      Object.assign(form, response.data);

      // 处理文件对象格式
      if (form.fileObjects) {
        form.fileObjects = form.fileObjects.map((t) => ({
          id: uuidv4(),
          name: t.fileName,
          url: t.filePath,
        }));
      }
    });
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}
</style>
